from functools import wraps
from flask import Blueprint, jsonify, redirect, render_template, request, session, url_for
from app.admin.utils import admin_required, admin_required_web
from app.models import db
from app.admin.models import Admin
from app.doctor.models import Doctor
from app.doctor.routes import doctor
from app.utils import process_request_data

admin = Blueprint('admin', __name__, template_folder='templates')

@admin.route('/login_admin', methods=['POST'])
def login_admin():
    # process data
    data = process_request_data(request)
    username = data.get('username')
    password = data.get('password')
    if not username or not password:
        return jsonify({"code": 1, 'message': 'Missing username or password'}), 400
    admin = Admin.query.filter_by(username=username).first()
    if admin and admin.check_password(password):
        # Valid credentials, set session or token for authentication
        # Example of storing admin_id in session
        session['admin_id'] = admin.id
        session['username'] = admin.username
        return jsonify({"code": 0, 'message': 'Login successful', "data": {"id": session["admin_id"], "username": session["username"]
                                                                           }})
    else:
        return jsonify({"code": 1, 'message': 'Invalid username or password'})


@admin.route('/logout_admin', methods=['POST'])
@admin_required
def logout_admin():
    session.pop('username', None)
    session.pop('admin_id', None)
    response = jsonify({"code": 0, 'message': 'Logout successful'})
    response.delete_cookie('session', path='/')
    return response

# tested


@admin.route('/add_admin', methods=['POST'])
@admin_required
def add_admin():
    # process data
    data = process_request_data(request)
    if Admin.query.filter_by(username=data.get('username')).first():
        return jsonify({"code": 1, 'message': 'Username already exists'}), 400
    try:
        new_admin = Admin(**data)
    except:
        return jsonify({"code": 1, 'message': 'Invalid request'}), 400
    try:
        db.session.add(new_admin)
        db.session.commit()
    except:
        return jsonify({"code": 1, 'message': 'Error adding admin'}), 500
    return jsonify({"code": 0, 'message': 'Admin added successfully', "data": {"id": new_admin.id, "username": new_admin.username}})


@admin.route('/modify_admin', methods=['POST'])
@admin_required
def modify_admin():
    # process data
    data = process_request_data(request)
    id = data.pop('id')

    admin_to_modify = Admin.query.get(id)
    if not admin_to_modify:
        return jsonify({"code": 1, 'message': 'Admin not found'}), 404
    admin_to_modify.modify(**data)

    db.session.commit()
    return jsonify({"code": 0, 'message': 'Admin modified successfully', "data": admin_to_modify.to_dict()})


@admin.route('/query_admin', methods=['POST'])
@admin_required
def query_admin():

    data = process_request_data(request)
    try:
        admins_to_query = Admin.query.filter_by(**data).all()
    except:
        return jsonify({"code": 1, 'message': 'Invalid request'}), 400
    return jsonify({"code": 0, 'message': 'Admins queried successfully', "data": [admin.to_dict() for admin in admins_to_query]})


@admin.route('/delete_admin', methods=['POST'])
@admin_required
def delete_admin():

    data = process_request_data(request)
    id = data.pop('id')
    if not id:
        return jsonify({"code": 1, 'message': 'id not in data'}), 400

    admin_to_delete = Admin.query.get(id)
    if not admin_to_delete:
        return jsonify({"code": 1, 'message': 'Admin not found'}), 404

    db.session.delete(admin_to_delete)
    db.session.commit()
    return jsonify({"code": 0, 'message': 'Admin deleted successfully'}), 200


@admin.route('/modify_doctor', methods=['POST'])
@admin_required
def modify_doctor():
    # process data
    data = process_request_data(request)
    doctor = Doctor.query.filter_by(data.get('id')).first()
    if doctor is None:
        return jsonify({"code": 1, 'message': 'Doctor not found'}), 404
    try:
        doctor.modify(**data)
    except:
        return jsonify({"code": 1, 'message': 'Invalid request'}), 400
    db.session.commit()
    return jsonify({"code": 0, 'message': 'Doctor modified successfully'})


# 用于跳转的根路由
@admin.route('/')
@admin_required_web
def root_admin():
    return redirect(url_for('admin.dashboard_admin_web'))

# 管理员面板
# 包含退出按钮
# 医生搜索框(可选字段id name username password 不填则全部搜索)
# 搜索结果为表格(带删除按钮)
# 多次搜索结果覆盖
# 添加医生输入框 username password name(可选) 
# 修改医生输入框 id username(可选) password(可选) name(可选)
# 请求和返回均为json
# 返回内的code为0则成功 否则网页需要给出alert失败信息json(message字段)
# 使用ajax而不是原生表单提交
@admin.route('/dashboard_admin_web')
@admin_required_web
def dashboard_admin_web():
    return render_template('admin/dashboard_admin_web.html')


# 用于跳转的退出登陆路由
@admin.route('/logout_admin_web')
def logout_admin_web():
    session.pop('username', None)
    session.pop('admin_id', None)
    return redirect(url_for('admin.root_admin'))


@admin.route('/login_admin_web')
def login_admin_web():
    return render_template('admin/login_admin_web.html')

